package com.xiangxiangjd.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.xiangxiangjd.bean.*;
import com.xiangxiangjd.bean.vo.ReturnDocx;
import com.xiangxiangjd.controller.helper.$;
import com.xiangxiangjd.mapper.ReturnDateNoMapper;
import com.xiangxiangjd.service.GoodsService;
import com.xiangxiangjd.service.ReturnDateNoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiangxiangjd.bean.result.ResultPage;
import com.xiangxiangjd.controller.model.ApiResultModel;

import com.xiangxiangjd.service.ReturnGoodsService;
import com.xiangxiangjd.service.UnitService;
import com.xiangxiangjd.utils.OddNumber;
import com.xiangxiangjd.utils.StringUtilsXiao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * 归还航材批次 服务实现类
 *
 * @author 肖守凯
 * @since 2021-11-08
 */
@Service
public class ReturnDateNoServiceImpl extends ServiceImpl<ReturnDateNoMapper, ReturnDateNo>
    implements ReturnDateNoService {

  //归还 物品中间表
  @Autowired ReturnGoodsService returnGoodsService;

//物品
  @Autowired
  GoodsService goodsService;

  @Autowired
  UnitService unitService;

  /**
   * 添加ReturnDateNo
   *
   * @param returnDateNo 前端传进的参数
   * @return 返回统一信息
   */
  @Transactional(isolation = Isolation.READ_COMMITTED)
  @Override
  public ApiResultModel addReturnDateNo(ReturnDateNo returnDateNo) {

    System.out.println(returnDateNo.toString());

    // 查询最后一次生成的单号
    String returnOddNumber = baseMapper.getLastReturnOddNumber();

    // 生成一个单号 申领  SL
    String ghOddNumber = OddNumber.getOddNumber("GH", returnOddNumber);

    // 给单号 插入
    returnDateNo.setReturnOddNumber(ghOddNumber);

    // 待归还
    returnDateNo.setReturnState("1");

    if (!this.save(returnDateNo)) {
      return $.error("该批次归还失败  请重新归还！");
    }
    //获取要归还的航材
    List<ReturnGoods> returnGoodsList = returnDateNo.getReturnGoodsList();
    returnGoodsList.stream().map(o->{
      o.setReturnId(returnDateNo.getId());
      return o;
    }).collect(Collectors.toList());


    boolean b = returnGoodsService.saveOrUpdateBatch(returnGoodsList);
    if(!b){
      throw new RuntimeException("归还失败 请联系管理员 查看数据库");
    }


    return $.success("等待管理员审批归还");
  }
  /**
   * 编辑跳转页面的回显数据ReturnDateNo
   *
   * @param id 前端传进的参数
   * @return 返回实体类
   */
  @Override
  public ReturnDateNo selectReturnDateNoByIdReturnDateNo(String id) {
    return this.getById(id);
  }

  /**
   * 编辑ReturnDateNo
   *
   * @param returnDateNo 前端传进的参数
   * @return 返回统一信息
   */
  @Override
  public ApiResultModel editReturnDateNo(ReturnDateNo returnDateNo) {
    if (this.updateById(returnDateNo)) {
      return $.success();
    } else {
      return $.error("编辑失败");
    }
  }
  /**
   * 删除一条ReturnDateNo
   *
   * @param ids 前端传进的ID
   * @return 返回统一信息
   */
  @Override
  public ApiResultModel delReturnDateNos(List ids) {

    int i = baseMapper.deleteBatchIds(ids);

    return $.success(i);
  }

  /**
   * 分页查询ReturnDateNo
   *
   * @param page 页码
   * @param limit 查几条
   * @param returnDateNo 前端传进的参数
   * @return 返回统一分页信息
   */
  @Override
  public ResultPage findReturnDateNoByPage(Integer page, Integer limit, ReturnDateNo returnDateNo) {
    Map<String, Object> paramMap = new HashMap<>();
    page = page == null ? 1 : page;
    limit = limit == null ? 20 : limit;

    paramMap.put("page", (page - 1) * limit);
    paramMap.put("limit", limit);
    paramMap.put("returnDateNo", returnDateNo);


    if (!StringUtilsXiao.isBlank(returnDateNo.getCreateTime())) {
      String[] createTime = returnDateNo.getCreateTime().split(",");

      if (createTime[0].equals(createTime[1])) {
        createTime[1] = String.valueOf((Long.valueOf(createTime[1]) + 24 * 60 * 60 * 1000) - 1);
      }
      paramMap.put("createTimeStart", createTime[0]);
      paramMap.put("createTimeEnd", createTime[1]);
    }



    List<ReturnDateNo> list = baseMapper.selectMyPage(paramMap);
    Integer count = baseMapper.countMyPage(paramMap);
    ResultPage<ReturnDateNo> resultPage = new ResultPage<>();
    resultPage.setCode(200);
    resultPage.setCount(count);
    resultPage.setMsg("成功");
    resultPage.setData(list);
    return resultPage;
  }

  /**
   * 审批
   * @param returnDateNoId
   * @param returnDateNoState
   * @return
   */

  @Transactional
  @Override
  public ApiResultModel returnApprove(Integer returnDateNoId, String returnDateNoState,String returnForFailure) {
    // 修改状态
    boolean update =
            this.update(
                    new LambdaUpdateWrapper<ReturnDateNo>()
                            .set(ReturnDateNo::getReturnState, returnDateNoState)
                            .set(ReturnDateNo::getReturnForFailure,returnForFailure)
                            .eq(ReturnDateNo::getId, returnDateNoId));

    // 审批通过修改
    if (returnDateNoState.equals("2")) {
      // 查询所有要归还的航材
      List<ReturnGoods> ReturnGoodsList =
              returnGoodsService.list(
                      new LambdaQueryWrapper<ReturnGoods>()
                              .eq(ReturnGoods::getReturnId, returnDateNoId));
      // 查询归还单号信息
      ReturnDateNo returnDateNo = this.getById(returnDateNoId);

      // 单件循环 验证交接
      for (ReturnGoods returnGoods : ReturnGoodsList) {

        // 开始交接
        boolean update1 = goodsService.update(
                new LambdaUpdateWrapper<Goods>()
                        .set(Goods::getUserId, "0")
                        .eq(Goods::getUserId, returnDateNo.getUserId())
                        .eq(Goods::getGoodsType, "1")
                        .eq(Goods::getId,returnGoods.getGoodsId())
        );
        if(!update1){
          throw new RuntimeException("该航材已交接 或者已归还："+returnGoods.getGoodsId());
        }

      }

    }

    return $.success("成功 改变状态");
  }


  /**
   *    归还单号详细信息
   * @param returnDateNoId
   * @return
   */
  @Override
  public ReturnDateNo returnApprove(Integer returnDateNoId) {

    return baseMapper.returnApprove(returnDateNoId);
  }

  @Override
  public Map downDocReturnDateNo(Integer claimDateNoId) {


    List<ReturnDocx> data=new ArrayList<>();

    //归还详细信息
    ReturnDateNo returnDateNo = returnApprove(claimDateNoId);

    //获取所有的归还物品
    List<ReturnGoods> returnGoodsList = returnDateNo.getReturnGoodsList();

    //判断相同的物品
    Map<Goods,Integer> map = new HashMap();


    //自增+1
    AtomicInteger i = new AtomicInteger(0);
    /**
     * 判断相同的物品进行累计
     */
    for (ReturnGoods returnGoods : returnGoodsList) {
      //当前物品
      Goods goods = returnGoods.getGoods();
      ReturnDocx returnDocx = new ReturnDocx();
      returnDocx.setSerialNumber(i.incrementAndGet());
      returnDocx.setGoodsName(goods.getGoodsName());
      returnDocx.setModel(goods.getModel());
      returnDocx.setCompany(goods.getCompany());
      returnDocx.setGoodsId(goods.getId());

      //拥有的数量
      int count = goodsService.count(new LambdaQueryWrapper<Goods>()
              .eq(Goods::getGoodsName, goods.getGoodsName())
              .eq(Goods::getModel, goods.getModel())
              .eq(Goods::getDateNoId, goods.getDateNoId())
              .eq(Goods::getUserId, returnDateNo.getUserId())
      );


      //归还后还剩余的数量
      returnDocx.setExistingNumber(Double.valueOf(count));
      //归还的数量
      returnDocx.setReturnNumber(1.0);

      returnDocx.setRemark(goods.getRemarks());

      data.add(returnDocx);

    }





    Map map1=new HashMap();
    map1.put("data",data);

    map1.put("date", new Date());

    Unit unit = unitService.getById(returnDateNo.getUnitId());
    String  affiliatedUnits=unit.getUnitName();

    map1.put("affiliatedUnits", affiliatedUnits);




    return map1;
  }
}
